﻿//===============================================================================
// File: RoleHelper.cs
// Author:Veiller Hu
// CLR Version：4.0.30319.1
// Created Date:  2011/2/20 10:01:26 PM 
// Summary:  
//===============================================================================
//
// Copyright (c) East China Information Technology Corporation. All rights reserved.
//
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
// KIND, WHETHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR
// PURPOSE.
//===============================================================================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace GPMS.BLL
{
    using GPMS.Model;
    using GPMS.Extension;
using System.Web.Mvc;
    public static class RoleHelper
    {
        /// <summary>
        /// 获得角色entity
        /// </summary>
        /// <param name="id">角色id</param>
        /// <param name="db">ExtendedGPMSDb</param>
        /// <returns></returns>
        public static Role Get(Guid id, ExtendedGPMSDb db)
        {
            return db.Roles.FirstOrDefault(r => r.RoleID == id);
        }

        /// <summary>
        /// 检查角色是否存在
        /// </summary>
        /// <param name="role"></param>
        /// <param name="db"></param>
        /// <returns></returns>
        public static bool IsExist(Role role, ExtendedGPMSDb db)
        {
            return db.Roles.Any(r => r.RoleID == role.RoleID && r.IsDeleted == false);
        }

        /// <summary>
        /// 检查角色是否存在
        /// </summary>
        /// <param name="roleName"></param>
        /// <param name="db"></param>
        /// <returns></returns>
        public static bool IsExist(string roleName, ExtendedGPMSDb db)
        {
            return db.Roles.Any(r => r.RoleName == roleName && r.IsDeleted == false);
        }

        /// <summary>
        /// 添加角色
        /// </summary>
        /// <param name="role"></param>
        /// <param name="db"></param>
        /// <returns></returns>
        public static Guid Add(Role role, ExtendedGPMSDb db)
        {
            if (role.RoleID==Guid.Empty)
            {
                role.RoleID = Guid.NewGuid();
            }
            if (IsExist(role.RoleName,db))
            {
                throw new DuplicateException();
            }
            role.CreateDate = DateTime.Now;
            role.IsDeleted = false;
            db.Roles.AddObject(role);
            db.SaveChanges();
            return role.RoleID;
        }

        /// <summary>
        /// 删除角色
        /// </summary>
        /// <param name="id"></param>
        /// <param name="db"></param>
        public static void Delete(Guid id, ExtendedGPMSDb db)
        {
            if (db.UserInfos.Any(u=>u.Roles.Any(r=>r.RoleID==id)))
            {
                throw new Exception("此角色还有用户，不能删除");
            }
            Role role = db.Roles.FirstOrDefault(r => r.RoleID == id);
            role.IsDeleted = true;
            db.SaveChanges();
        }

        /// <summary>
        /// 更新权限信息
        /// </summary>
        /// <param name="permission">权限信息</param>
        /// <param name="collection">表单集合</param>
        /// <returns></returns>
        public static List<PermissionVM> UpdatePermission(List<PermissionVM> permission, FormCollection collection)
        {
            foreach (var item in collection.AllKeys)
            {
                permission.SingleOrDefault(p => p.ActionInfo.ActionID == Guid.Parse(item))
                    .Permission = (bool)collection.GetValue(item).ConvertTo(typeof(bool));
            }
            return permission;
        }

        /// <summary>
        /// 获得权限列表
        /// </summary>
        /// <param name="id">角色id</param>
        /// <param name="db">ExtendedGPMSDb</param>
        /// <returns></returns>
        public static List<PermissionVM> GetPermission(Guid id, ExtendedGPMSDb db)
        {
            //权限无关链接信息
            List<string> noVerify = NoVerify.Get();
            List<string> linkless = NoVerify.GetLinklessController();
            return db.ActionInfos
                .Where(a=>
                    !noVerify.Contains(a.ActionName.ToLower()) &&
                        !linkless.Contains(a.ControllerInfo.ControllerName.ToLower())
                )
                .ToList()
                .Select(a => new PermissionVM
                {
                    ActionInfo = a,
                    ControllerID = a.ControllerID,
                    ControllerName = a.ControllerInfo.ControllerName,
                    Permission = a.Roles.Any(r => r.RoleID == id)
                }).OrderBy(a=>a.ControllerName).ToList();
        }

        /// <summary>
        /// 保存权限信息
        /// </summary>
        /// <param name="id">角色id</param>
        /// <param name="collection">表单集合</param>
        /// <param name="db">ExtendedGPMSDb</param>
        public static void SavePermission(Guid id,FormCollection collection, 
            ExtendedGPMSDb db)
        {
            //获得权限列表
            List<PermissionVM> permission = GetPermission(id, db);
            //根据页面数据更新权限列表
            foreach (var item in collection.AllKeys)
            {
                permission
                    .SingleOrDefault(p => p.ActionInfo.ActionID == 
                        Guid.Parse(item))
                    .Permission = (bool)collection.GetValue(item)
                    .ConvertTo(typeof(bool));
            }
            //保存权限列表
            permission.ForEach(p =>
                {
                    Role role = db.Roles.FirstOrDefault(r => r.RoleID == id);
                    bool contain = db.Roles
                                .FirstOrDefault(r => r.RoleID == id)
                                .ActionInfos
                                .Contains(p.ActionInfo);
                    if (p.Permission && !contain)
                    {
                        role.ActionInfos.Add(p.ActionInfo);
                    }
                    else if(!p.Permission && contain)
                    {
                        role.ActionInfos.Remove(p.ActionInfo);
                    }
                });
            db.SaveChanges();
        }
    }
}
